Note that we use Django ’ s built in User model (imported at the second line from the top) as the creator of the todo.

Analyze Code

title = models.CharField(max_length=100)

memo = models.TextField(blank=True)

#set to current time

created = models.DateTimeField(auto_now_add=True)

completed = models.BooleanField(default=False)

#user who posted this

user = models.ForeignKey(User, on_delete=models.CASCADE)

We then have the properties of the model. Notice that the properties have types like CharField, TextField,

DateTimeField. Django provides many other model fields to support common types like dates, integers, emails, etc.

To have a complete documentation of the kinds of types and how to use them, refer to the Model field reference in

the Django documentation (https://docs.djangoproject.com/en/4.0/ref/models/fields/).

If any of the above feels new to you, it will be good to pause here and review Beginning Django (contact

[email protected]) for more explanation of traditional Django.

Analyze Code

def __str__(self):

return self.title

We also include a __str__ method so that the title of a todo will display in the admin later on.

With this model, we can create a Todo table in our database.

Migrations

Whenever we create a new model or make changes to it in models.py, we need to update Django in a two-step

process. First, in /todoapp/todobackend/, we create a migration file with the makemigrations command:

Execute in Terminal

python3 manage.py makemigrations

This generates the SQL commands (migrations) for preinstalled apps in our INSTALLED_APPS setting. The SQL

commands are not yet executed but are just a record of all changes to our models. The migrations are stored in an

auto-generated folder migrations (fig. 1).

Figure 1

Second, we build the actual database with the following:

Execute in Terminal

python3 manage.py migrate

The migrate command creates an initial database based on Django ’ s default settings and executes the SQL

commands in the migrations file. Notice there is a db.sqlite3 file in the project folder. The file represents our SQLite

database. It is created the first time we run migrate. migrate syncs the database with the current state of any

database models in the project and listed in INSTALLED_APPS. It is thus essential that after we update a model,

we need to run migrate.

In summary, each time you make changes to a model file, you have to run:

Analyze Code

python3 manage.py makemigrations

python3 manage.py migrate

* Contact [email protected] for the source code of the completed project